import { ComponentInternalInstance, getCurrentInstance } from 'vue';

export function getData(baseURL: string) {
  return function (url: string, query?: Record<string, any>) {
    if (!baseURL.match(/(\/)$/)) {
      baseURL += '/';
    }
    url = baseURL + (url.startsWith('/') ? url.substr(1) : url);
    if (query) {
      let queryStr = '?';
      for (let key in query) {
        if (Object.prototype.hasOwnProperty.call(query, key)) {
          queryStr += `${key}=${String(query[key])}&`;
        }
      }
      url = url.replace(/(\/)$/, '') + queryStr.replace(/(&)$/, '');
    }
    return new Promise<{ data: any; status: number }>((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.onreadystatechange = function () {
        if (xhr.readyState !== 4) {
          return;
        }
        if (this.status >= 200 && this.status < 300) {
          resolve({
            data: this.response,
            status: this.status,
          });
        } else {
          reject(new Error(this.statusText));
        }
      };
      xhr.onerror = function () {
        reject(new Error(this.statusText));
      };

      xhr.responseType = 'json';

      xhr.setRequestHeader('Content-Type', 'application/json');
      // xhr.setRequestHeader('Accept', 'application/json');
      // no-cache
      xhr.setRequestHeader('If-Modified-Since', '0');

      xhr.send(null);
    });
  };
}

export type HttpConfig = {
  baseURL?: string;
};

export function useHttp(
  cfg: HttpConfig = {}
): { get: ReturnType<typeof getData> } {
  let vm: ComponentInternalInstance | null;
  if ((vm = getCurrentInstance())) {
    return vm.appContext.config.globalProperties.$http;
  }
  return {
    get: getData(cfg.baseURL || '/'),
  };
}
